package org.example.pet.common;

import lombok.extern.slf4j.Slf4j;
import org.example.pet.common.expection.AuthenticationException;
import org.example.pet.common.expection.CustomException;
import org.example.pet.common.expection.PermissionException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL异常处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return Result.err(msg);
        }

        return Result.err("未知错误");
    }

    /**
     * 业务异常处理
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return Result.err(ex.getMessage());
    }

    /**
     * 认证异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result<String> exceptionHandler(AuthenticationException ex){
        log.error(ex.getMessage());
        return Result.err(-1, ex.getMessage());
    }

    /**
     * 权限异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(PermissionException.class)
    public Result<String> exceptionHandler(PermissionException ex){
        log.error(ex.getMessage());
        return Result.err(-2, ex.getMessage());
    }

    /**
     * 未知异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception ex){
        log.error(ex.getMessage());
        return Result.err("未知错误");
    }
}
